# author: tgl

from rest_framework import serializers
from apps.api.interface.models import InterfaceModel
from apps.api.project.models import ProjectModel
from apps.api.testcase.serializers import TestCaseNameModelSerializer
from apps.api.config.serializers import ConfigNameModelSerializer
from utils.common import date_format


class InterfaceModelSerializer(serializers.ModelSerializer):

    # 序列化时，project默认取表里的整数值，这里将响应数据中的project字段取值改为项目名称，取项目模型的__str__返回值
    project = serializers.StringRelatedField(label='所属项目名称', help_text='所属项目名称')
    project_id = serializers.PrimaryKeyRelatedField(queryset=ProjectModel.objects.all(), label='所属项目ID',
                                                    help_text='所属项目ID')

    class Meta:
        model = InterfaceModel
        exclude = ["is_delete", "update_time"]
        extra_kwargs = {
            "name": {
                "min_length": 2,
                "max_length": 50,
                "error_messages": {
                    "min_length": "接口名称长度为 2-50 个字符！",
                    "max_length": "接口名称长度为 2-50 个字符！"
                }
            },
            "create_time": {
                "read_only": True,
                "format": date_format()
            }
        }

    def create(self, validated_data):
        project = validated_data.pop("project_id")
        validated_data["project_id"] = project.id
        return super().create(validated_data)

    def update(self, instance, validated_data):
        project = validated_data.pop("project_id")
        validated_data["project_id"] = project.id
        return super().update(instance, validated_data)


class InterfaceAndTestCaseNameModelSerializer(serializers.ModelSerializer):

    testcase = TestCaseNameModelSerializer(label="接口用例", help_text="接口用例", many=True, read_only=True)

    class Meta:
        model = InterfaceModel
        fields = ["id", "name", "testcase"]


class InterfaceAndConfigNameModelSerializer(serializers.ModelSerializer):

    config = ConfigNameModelSerializer(label="接口配置", help_text="接口配置", many=True, read_only=True)

    class Meta:
        model = InterfaceModel
        fields = ["id", "name", "config"]


class RunInterfaceModelSerializer(serializers.ModelSerializer):
    env_id = serializers.IntegerField(label="运行环境id", help_text="运行环境id", write_only=True)

    class Meta:
        model = InterfaceModel
        fields = ["env_id"]
